package com.lv7.service.impl;

import com.lv7.dao.KeyGeneratorDao;
import com.lv7.service.KeyGeneratorService;
import com.lv7.core.util.date.TimeHelper;
import com.lv7.core.util.helper.TextHelper;
import com.lv7.core.util.helper.ValidateHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 唯一键生成器
 * @author Oven
 *
 */
@Service
public class KeyGenerator implements KeyGeneratorService {
	
	@Autowired
	private KeyGeneratorDao keyGeneratorDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public String generateKey(String prefix, String table, String column, int length) {
		return generateKey(prefix, table, column, null, length);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public String generateDailyKey(String prefix, String table, String column, int length) {
		return generateKey(prefix, table, column, TimeHelper.getCurrentLocalTime("yyyyMMdd"), length);
	}
	
	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public String generateKey(String prefix, String table, String column, String date, int length){
		
		try {
			int seq = 0;	//序列号
			int target = 0;		//更新后的序列值
			
			//查询对应的序列
			Map<String, Object> keySequence = keyGeneratorDao.getKeySequence(table, column);
			String currentLocalTime = TimeHelper.getCurrentLocalTime("yyyyMMddHHmmss");
			if(ValidateHelper.isNullOrEmpty(keySequence)){
				target = 1;
				keyGeneratorDao.addKeySequence(table, column, currentLocalTime, target);
			} else {
				//当前序列时间
				String time = keySequence.get("time").toString();
				//当前序列号
				seq = Integer.parseInt(keySequence.get("sequence").toString());
				//判断是否限制当天的内容，是则seq+1，否则seq=1
				if(ValidateHelper.isNullOrEmpty(date) || time.startsWith(date)){
					target = seq + 1;
				} else {
					target = 1;
				}
				//更新失败，并发量高时会导致序号已经被更新，此时重新再去执行生成
				if(keyGeneratorDao.updateKeySequence(table, column, currentLocalTime, seq, target) == 0){
					return generateKey(prefix, table, column, date, length);
				}
			}
			
			return prefix + date + TextHelper.fillWithZero(target, length);
		} catch (Exception e) {
			//异常重新生成，必须出现一个可用的ID
			return generateKey(prefix, table, column, date, length);
		}
	}
}
